package com.naiterui.ehp.bs.pharmacist.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;

import lombok.SneakyThrows;

/**
 * 电子签名印章图片生成
 *
 * @author guoyongxiang
 * @date 2019-07-26 17:12
 * @since 1.0.0
 */
public class SealImageUtil {

    @SneakyThrows
    public static String graphicsNameSealGeneration(String text) {
        BufferedImage image = generationBufferedImage(text);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        return Base64.getEncoder().encodeToString(stream.toByteArray());
    }

    @SneakyThrows
    public static boolean graphicsNameSealGeneration(String text, String path) {
        BufferedImage image = generationBufferedImage(text);
        File file = new File(path);
        FileUtils.forceMkdirParent(file);
        return ImageIO.write(image, "PNG", file);
    }

    private static BufferedImage generationBufferedImage(String text) {
        // 实际数据行数+标题+备注
        int imageWidth = 80;
        int imageHeight = 40;

        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();

        Color red = new Color(237, 123, 117);
        g2d.setColor(red);
        g2d.setStroke(new BasicStroke(2.0f));

        // 画边框
        g2d.drawRect(4, 4, imageWidth - 4 * 2, imageHeight - 4 * 2);

        // 抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);// 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        // 设置字体
        Font font = new Font("楷体", Font.BOLD, 16);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics(font);

        int textWidth = fm.stringWidth(text);
        int textWidthX = (imageWidth - textWidth) / 2;
        g2d.drawString(text, textWidthX, 26);

        g2d.dispose();
        return image;
    }
}
